﻿using System;
using System.Diagnostics;

namespace Lenic.DI.Lifetimes
{
    /// <summary>
    /// 单例生存周期类【在容器生存周期内有且只会有一个实例对象】
    /// </summary>
    [DebuggerStepThrough]
    public class SingleLifetime : LifetimeBase
    {
        private object instance = null;

        #region LifetimeBase

        protected override object GetValue<T>(string name, Func<Delegate, T> action)
        {
            if (instance == null)
            {
                lock (this)
                {
                    if (instance == null)
                        instance = action(Function);
                }
            }
            return instance;
        }

        protected override void Disposing()
        {
            if (instance is IDisposable)
                ((IDisposable)instance).Dispose();
        }

        #endregion LifetimeBase
    }
}